package com.world.cat.service.back;

import com.world.cat.dao.back.HandleLogDao;
import com.world.cat.dao.sys.UploadRelationDao;
import com.world.cat.model.back.HandleLog;
import com.world.cat.model.sys.UploadRelation;
import com.world.cat.service.sys.BaseService;
import com.world.cat.app.utils.qiniu.UploadUtil;
import com.world.common.pojo.Result;
import com.world.common.util.CollectionUtil;
import com.world.core.dao.GenericRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class HandleLogService extends BaseService<HandleLog> {
    @Resource
    private HandleLogDao handleLogdao;
    @Resource
    private UploadRelationDao uploadRelationDao;

    @Override
    public GenericRepository getDao() {
        return handleLogdao;
    }

    public List<HandleLog> getList(String objId) {
        List<HandleLog> handleLogs = handleLogdao.findByObjId(objId);
        if (CollectionUtil.isNotEmpty(handleLogs)) {
            Set<String> ids = new HashSet<>();
            for (HandleLog handleLog : handleLogs) {
                ids.add(handleLog.getId());
            }
            List<UploadRelation> uploadRelations = uploadRelationDao.findByObjIdIn(ids);
            if (CollectionUtil.isNotEmpty(uploadRelations)) {
                Map<String, List<String>> objFileRelationMap = new HashMap<>();
                for (UploadRelation uploadRelation : uploadRelations) {
                    List<String> relations = objFileRelationMap.get(uploadRelation.getObjId());
                    if (relations == null) {
                        relations = new ArrayList<>();
                        objFileRelationMap.put(uploadRelation.getObjId(), relations);
                    }
                    relations.add(UploadUtil.getFullDownLoadUrlByFileId(uploadRelation.getFileId()));
                }

                for (HandleLog handleLog : handleLogs) {
                    handleLog.setFiles(objFileRelationMap.get(handleLog.getId()));
                }
            }
        }
        return handleLogs;
    }

    public List<HandleLog> getLatest(String username, Integer limit) {
        String hql = "select t from HandleLog t,Case c where t.objId=c.id and c.creator='" + username + "' order by t.createTime desc";
        List<HandleLog> handleLogs = handleLogdao.findByHql(hql, limit);
        return handleLogs;
    }

    public Result saveHandleLog(String objId, String title, String handleAction, String content, String remark) {
        HandleLog handleLog = new HandleLog(objId, title, handleAction, content, remark);
        handleLogdao.save(handleLog);
        return new Result(true);
    }
}
